<?php

$ARGV_FLAG_FILE = $argv[1];
$ARGV_FLAG_URL = $argv[2];

$LOCK_RUN_FILE=dirname(__FILE__).'/Lock-'.$ARGV_FLAG_FILE.'-'.$ARGV_FLAG_URL.'.txt';
if(file_exists($LOCK_RUN_FILE)){
	die('LockFile['.$LOCK_RUN_FILE.'] Exists!');
}
file_put_contents($LOCK_RUN_FILE,date('Y-m-d H:i:s'));

$urllibs = array();

$costtime0file = dirname(__FILE__) . '/costurl' . $ARGV_FLAG_URL . '.txt';
$dataurlarray = file($costtime0file);
foreach ($dataurlarray as $urlt) {
    $urllibs[] = trim($urlt);
}unset($urlt);

$opts = array(
    'http' => array(
        'method' => "GET",
        'timeout' => 10,
    )
);
$context = stream_context_create($opts);

$localIp = file_get_contents('http://imail.sinaapp.com/ip.php', false, $context);
if (!$localIp) {
    $localIp = file_get_contents('http://imail.sinaapp.com/ip.php', false, $context);
}

require_once dirname(__FILE__) . '/autoload.php';
$errorURLs = array();
$arrERROR_Host = array();

function multiple_threads_request($connomains) {
    global $errorURLs;
	global $arrERROR_Host;
    $intOK = $intError = $intWarning = 0;
    $mh = curl_multi_init();
    foreach ($connomains as $i => $url) {
		$arrURLP=parse_url($url);
		if(in_array($arrURLP['host'],$arrERROR_Host)){
			continue;
		}
        log::n($url);
        $conn[$i] = curl_init($url);
        curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1); //返回信息  
        curl_setopt($conn[$i], CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($conn[$i], CURLOPT_TIMEOUT, 15);
        curl_multi_add_handle($mh, $conn[$i]);
    }
// start performing the request
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);

    while ($active and $mrc == CURLM_OK) {
        // wait for network
        if (curl_multi_select($mh) != -1) {
            // pull in any new data, or at least handle timeouts
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }
    if ($mrc != CURLM_OK) {
        $intError++;
        log::w("Curl multi read error $mrc");
    }

    foreach ($connomains as $i => $url) {
        if (($err = curl_error($conn[$i])) == '') {
            $res[$i] = curl_multi_getcontent($conn[$i]);
            $intOK++;
        } else {
            $intWarning++;
            $errorURLs[] = $url;
			$arrURLINFO=parse_url($url);
			//$arrERROR_Host[] = $arrURLINFO['host'];
            log::w("Curl error on handle $i: $err");
        }
        curl_multi_remove_handle($mh, $conn[$i]);
        curl_close($conn[$i]);
    }
    curl_multi_close($mh);

    return array('ok' => $intOK, 'error' => $intError, 'warning' => $intWarning);
}

function sendwlM($domain) {
    $mrand = 10;
    global $urllibs;
    $intOK = $intError = $intWarning = 0;
    $murls = array();
    foreach ($urllibs as $k => $url) {
        $curl = str_replace('(*)', $domain, $url);
        $murls[] = $curl;
        if ($k % $mrand == 1) {
            log::n('s_multiple_threads_request:' . count($murls));
            $res = multiple_threads_request($murls);
            log::n('e_multiple_threads_request:' . count($murls));
            $murls = array();
            $intOK+=$res['ok'];
            $intError+=$res['error'];
            $intWarning+=$res['warning'];
        }
    }
    log::n('multiple_threads_request:' . count($murls));
    $res = multiple_threads_request($murls);
    $intOK+=$res['ok'];
    $intError+=$res['error'];
    $intWarning+=$res['warning'];
    return array('ok' => $intOK, 'error' => $intError, 'warning' => $intWarning);
}

$timeStart = time();

$domainfile = dirname(__FILE__) . '/s100-domain-' . $ARGV_FLAG_FILE . '.php';
if (!file_exists($domainfile)) {
    die('!file_exists($domainfile)');
}
$arrUniqDomainDataUniq = json_decode(file_get_contents($domainfile), true);
$arrUniqDomainDataUniq = array_filter($arrUniqDomainDataUniq);
$arrUniqDomainDataUniq = array_unique($arrUniqDomainDataUniq);

shuffle($arrUniqDomainDataUniq);

$TotalCount = count($arrUniqDomainDataUniq);
$WarningCount = 0;

$HTMLBODY = '';
$HTMLBODY.= '<b>外链工具运行报告(网站个数:' . $TotalCount . '个)：</b>
          <table border="1" width="100%" bordercolorlight="#C0C0C0" bordercolordark="#C0C0C0" style="border-collapse: collapse;font-size: 14px;">';
$HTMLBODY.='<tr height="35">
    <td width="150">域名&nbsp;</td>
    <td width="150">发生时间&nbsp;</td>
    <td width="100">请求次数</td>
    <td width="100">单域名请求耗时</td></tr>
    ';

foreach ($arrUniqDomainDataUniq as $url) {
    $sonTimeStart = time();
    $arrResult = sendwlM(str_replace('http://', '', $url));
    $sonTimeEnd = time();
    $HTMLBODY.='<tr height="35">
    <td width="150"><font' . $color . '>' . str_replace('http://', '', $url) . '</font></td>
    <td width="150">' . date('Y-m-d H:i:s') . '</td>
    <td width="100"><font color="green">ok:' . $arrResult['ok'] . '</font>/err:<font color="red">' . $arrResult['error'] . '|wf:' . $arrResult['warning'] . '</font>&nbsp;</td>
    <td width="100"><font' . $color . '>' . ($sonTimeEnd - $sonTimeStart) . '秒</font>&nbsp;</td></tr>
    ';
}

$HTMLBODY.='</table>';
$arrUsers = array(
    'think889977@yeah.net',
);

$timeEnd = time();
$HTMLBODY.='<hr/>' . __FILE__;
$HTMLBODY.='<hr />[' . $localIp . ']总计耗时:' . ($timeEnd - $timeStart) . '秒<hr />' . print_r($errorURLs);
#post_email('外链' . basename(__FILE__) . '工具运行报告[fileflag:' . $ARGV_FLAG_FILE . '][urlflag:' . $ARGV_FLAG_URL . '][' . date('Y-m-d H:i:s') . ']', $HTMLBODY, $arrUsers);

unlink($LOCK_RUN_FILE);
?>